package com.qeegoo.b2bautozityp.moudle.good.viewmodel;

import android.databinding.ObservableArrayList;
import android.databinding.ObservableField;
import android.databinding.ObservableList;
import android.text.TextUtils;

import com.cropper.imagepicker.ImagePicker;
import com.kelin.mvvmlight.command.ReplyCommand;
import com.qeegoo.b2bautozityp.BR;
import com.qeegoo.b2bautozityp.R;
import com.qeegoo.b2bautozityp.api.HttpParams;
import com.qeegoo.b2bautozityp.api.ProgressSubscriber;
import com.qeegoo.b2bautozityp.api.RequestApi;
import com.qeegoo.b2bautozityp.api.RetrofitService;
import com.qeegoo.b2bautozityp.moudle.good.model.GoodsPropertyBean;
import com.qeegoo.b2bautozityp.moudle.good.model.ImageDetailUploadBean;
import com.qeegoo.b2bautozityp.moudle.goods.model.GoodsDetailResult;
import com.qeegoo.b2bautozityp.utils.ImgUtils;
import com.qeegoo.b2bautozityp.widget.ChoosePicDialog;

import java.io.File;
import java.util.Map;

import base.lib.util.ActivityManager;
import base.lib.util.ToastUtils;
import me.tatarka.bindingcollectionadapter.ItemView;
import me.tatarka.bindingcollectionadapter.ItemViewSelector;
import rx.Observable;

/**
 * 王少岩 在 2017/9/15 创建了它
 */

public class GoodsInfoViewModel {
    private GoodsPropertyBean mPropertyBean;
    private ImagePicker mImagePicker;
    public ObservableField<String> pj_info = new ObservableField<>("");//编辑信息
    public ObservableField<String> detailUrl = new ObservableField<>("");
    public ObservableField<Integer> commonPic = new ObservableField<>(R.mipmap.ic_switch_close);
    public ObservableField<Integer> askPic = new ObservableField<>(R.mipmap.ic_switch_close);
    public ObservableField<Integer> jyjPic = new ObservableField<>(R.mipmap.ic_switch_close);
    public ObservableField<Boolean> isCcj = new ObservableField<>(false);
    public ReplyCommand commonCommand = new ReplyCommand(() -> commonPic.set(commonPic.get() == R.mipmap.ic_switch_close ? R.mipmap.ic_switch_open : R.mipmap.ic_switch_close));
    public ReplyCommand askCommand = new ReplyCommand(() -> askPic.set(askPic.get() == R.mipmap.ic_switch_close ? R.mipmap.ic_switch_open : R.mipmap.ic_switch_close));
    public ReplyCommand jyjCommand = new ReplyCommand(() -> jyjPic.set(jyjPic.get() == R.mipmap.ic_switch_close ? R.mipmap.ic_switch_open : R.mipmap.ic_switch_close));

    public ObservableList<GoodsImgViewModel> items = new ObservableArrayList<>();
    public ItemView itemView = ItemView.of(BR.viewModel, R.layout.adapter_goods_img);

    public ObservableList<GoodsInfoItemViewModel> items_info = new ObservableArrayList<>();
    public ItemViewSelector<GoodsInfoItemViewModel> itemView_info = new ItemViewSelector<GoodsInfoItemViewModel>() {
        @Override
        public void select(ItemView itemView, int position, GoodsInfoItemViewModel item) {
            itemView.set(BR.viewModel, item.selectable.get() ? R.layout.adapter_goods_info : R.layout.adapter_goods_info_edit);
        }

        @Override
        public int viewTypeCount() {
            return 2;
        }
    };

    private RequestApi mRequestApi;

    public GoodsInfoViewModel(RequestApi requestApi) {
        mRequestApi = requestApi;
    }

    public void setImgs(ImagePicker imagePicker) {
        mImagePicker = imagePicker;
        items.add(new GoodsImgViewModel(mRequestApi, imagePicker));
        items.add(new GoodsImgViewModel(mRequestApi, imagePicker));
        items.add(new GoodsImgViewModel(mRequestApi, imagePicker));
        items.add(new GoodsImgViewModel(mRequestApi, imagePicker));
        items.add(new GoodsImgViewModel(mRequestApi, imagePicker));
    }

    public void setGoodsDetails(GoodsDetailResult goodsDetailResult, GoodsPropertyBean goodsPropertyBean) {
        mPropertyBean = goodsPropertyBean;
        for (int i = 0; i < goodsDetailResult.listImg.size(); i++) {
            items.get(i).setGoodsId(goodsDetailResult.goods.id);
            items.get(i).imgId.set(goodsDetailResult.listImg.get(i).id);
            items.get(i).imgUrl.set(goodsDetailResult.listImg.get(i).middleImagePath);
            items.get(i).showDel.set(!TextUtils.isEmpty(goodsDetailResult.listImg.get(i).middleImagePath));
        }
        commonPic.set(goodsDetailResult.goods.general.equals("1") ? R.mipmap.ic_switch_open : R.mipmap.ic_switch_close);
        isCcj.set(goodsDetailResult.goods.goodsType.equals("2"));
        items_info.addAll(GoodsInfoItemViewModel.getList(this, goodsDetailResult, goodsPropertyBean));
    }

    public void setLabelInfo(String label, String code, String name) {
        Observable.from(items_info)
                .filter(goodsInfoItemViewModel -> goodsInfoItemViewModel.labelText.get().equals(label))
                .subscribe(goodsInfoItemViewModel -> {
                    goodsInfoItemViewModel.code.set(code);
                    goodsInfoItemViewModel.infoText.set(name);
                });
        if (label.equals("配件品质")) {
            isCcj.set(name.equals("拆车件"));
        }

        if (items_info.size() == 12) {
            if (label.equals("配件品质") && name.equals("拆车件")) {
                Observable.from(items_info)
                        .filter(goodsInfoItemViewModel -> goodsInfoItemViewModel.labelText.get().equals("OE"))
                        .subscribe(goodsInfoItemViewModel -> goodsInfoItemViewModel.iconLeft.set(0));
                Observable.from(items_info)
                        .filter(goodsInfoItemViewModel -> goodsInfoItemViewModel.labelText.get().equals("配件品牌"))
                        .subscribe(goodsInfoItemViewModel -> {
                            goodsInfoItemViewModel.labelText.set("配件成色");
                            goodsInfoItemViewModel.infoHint.set("请选择配件成色");
                            goodsInfoItemViewModel.infoText.set("");
                            goodsInfoItemViewModel.setProperties(mPropertyBean.productQualityList);
                        });
                items_info.remove(items_info.size() - 1);
                items_info.remove(items_info.size() - 1);
            }
        } else if (items_info.size() == 10) {
            if (label.equals("配件品质") && !name.equals("拆车件")) {
                Observable.from(items_info)
                        .filter(goodsInfoItemViewModel -> goodsInfoItemViewModel.labelText.get().equals("OE"))
                        .subscribe(goodsInfoItemViewModel -> goodsInfoItemViewModel.iconLeft.set(R.mipmap.star));
                Observable.from(items_info)
                        .filter(goodsInfoItemViewModel -> goodsInfoItemViewModel.labelText.get().equals("配件成色"))
                        .subscribe(goodsInfoItemViewModel -> {
                            goodsInfoItemViewModel.labelText.set("配件品牌");
                            goodsInfoItemViewModel.infoHint.set("请选择配件品牌");
                            goodsInfoItemViewModel.infoText.set("");
                        });

                items_info.add(new GoodsInfoItemViewModel(this, 0, 0, "规格型号", "", "请输入规格型号", true));
                items_info.add(new GoodsInfoItemViewModel(this, 0, 0, "出厂编号", "", "请输入出厂编号", true));
            }
        }

    }

    public Map<String, String> getBaseInfoParam(Map<String, String> map) {
        boolean flag = false;
        for (GoodsInfoItemViewModel itemViewModel : items_info) {
            if (itemViewModel.iconLeft.get() == R.mipmap.star && TextUtils.isEmpty(itemViewModel.infoText.get())) {
                flag = true;
                ToastUtils.showToast(itemViewModel.infoHint.get());
                break;
            }
        }
        if (flag) {
            map.clear();
            return map;
        }
        map.put("productType", items_info.get(0).code.get());
        map.put("oemCode", items_info.get(1).infoText.get());
        map.put("oemName", items_info.get(2).infoText.get());
        map.put("quantity", items_info.get(3).infoText.get());
        map.put("warehouseId", items_info.get(4).code.get());
        map.put("productId", items_info.get(5).code.get());
        map.put("brandId", isCcj.get() ? "" : items_info.get(6).code.get());
        map.put("goodsRemark", items_info.get(8).infoText.get());
        map.put("goodsUnitId", items_info.get(9).code.get());
        map.put("goodsStyle", isCcj.get() ? "" : items_info.get(10).infoText.get());
        map.put("serialNumber", isCcj.get() ? "" : items_info.get(11).infoText.get());
        map.put("productQuality", isCcj.get() ? items_info.get(6).code.get() : "");
        map.put("general", commonPic.get() == R.mipmap.ic_switch_close ? "0" : "1");
        map.put("showTag", askPic.get() == R.mipmap.ic_switch_close ? "1" : "0");
        map.put("goodsType", isCcj.get() ? "2" : ((jyjPic.get() == R.mipmap.ic_switch_close) ? "1" : "0"));
        StringBuilder sb_ids = new StringBuilder();
        StringBuilder sb_urls = new StringBuilder();
        StringBuilder sb_rows = new StringBuilder();
        int i = 1;
        for (GoodsImgViewModel viewModel : items) {
            sb_ids.append(viewModel.imgId.get()).append(",");
            sb_urls.append(viewModel.imgUrl.get()).append(",");
            sb_rows.append(i++).append(",");
        }
        map.put("imageIds", sb_ids.substring(0, sb_ids.length() - 1));
        map.put("imageUrls", sb_urls.substring(0, sb_urls.length() - 1));
        map.put("imageRowNums", sb_rows.substring(0, sb_rows.length() - 1));
        map.put("goodsDetails", pj_info.get());
        return map;
    }

    public ReplyCommand uploadDetailImgCommand = new ReplyCommand(() ->
            new ChoosePicDialog(ActivityManager.getActivity(), mImagePicker, imageUri -> {
                File tmp = ImgUtils.getTempFile();
                ImgUtils.compressBmpToFile(ActivityManager.getActivity(), imageUri.getPath(), tmp);
                mRequestApi.uploadDetailImage(HttpParams.uploadDetailImage(tmp))
                        .compose(RetrofitService.applySchedulers())
                        .map(new RetrofitService.HttpResultFunc<>())
                        .subscribe(new ProgressSubscriber<ImageDetailUploadBean>() {
                            @Override
                            public void onNext(ImageDetailUploadBean imageUploadBean) {
                                pj_info.set("<img src=\"" + imageUploadBean.tempImagePath.get(0) + "\" />");
                                detailUrl.set(imageUri.toString());
                            }
                        });
            }).show());

}
